package com.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;

//处理get方式乱码问题
/**
 * 处理get方式的乱码思路是：我们在调用request.getParameter()的方法的时候，request的编码是
 * iso8859-1，所以拿到的是乱码。我们需要重新new之后就正常了，那现在我们的思路是我把reqeust对象包装一下
 * 重写getParameter()方法，这样，放行后的请求是我们包装后的请求对象，调用的getParameter()方法就是
 * 我们重写的getParameter()方法，在此方法中做中文处理后，这样，在servlet中拿到的就是正常的中文了。
 * 
 */
public class SetCharacterSetFilter implements Filter {

	public void init(FilterConfig filterConfig) throws ServletException {
	}
	
	public void destroy() {
	}

	public void doFilter(ServletRequest req, ServletResponse res,
			FilterChain chain) throws IOException, ServletException {
		// 将请求和响应转换为与协议相关的请求和响应
		HttpServletRequest request;
		HttpServletResponse response;
		try {
			request = (HttpServletRequest) req;
			response = (HttpServletResponse) res;
		} catch (ClassCastException e) {
			throw new ServletException("non-HTTP request or response");
		}
		
		MyHttpServletRequest myreq = new MyHttpServletRequest(request) ;
		
		//放行的是包装后的请求
		chain.doFilter(myreq, response) ;
	}
	
	class MyHttpServletRequest extends HttpServletRequestWrapper{

		private HttpServletRequest request ;
		
		public MyHttpServletRequest(HttpServletRequest request) {
			super(request) ;
			this.request = request ;
		}
		
		@Override
		public String getParameter(String name) {
			//拿到请求的请求方式，判断，如果是get请求，则处理，post方式直接放过
			String method = request.getMethod() ;
			String data = request.getParameter(name) ;
			System.out.println("data:" + data);
			if("post".equalsIgnoreCase(method))
				return data;
			else
				try {
					data = new String(data.getBytes("iso8859-1"),"UTF-8");
				} catch (Exception e) {
					e.printStackTrace();
				}
			return data ;
		}
		
	}
}
